import React, { Component } from 'react';
import { render } from 'react-dom';
import {Link} from 'react-router-dom'
require('../public/css/mycss.css');
export default class EditMessage extends React.Component{
    // 构造
    constructor(props) {
        super(props);
        this.state = {
            user:{},  //留言id值 和uaserName
            getmsg:{},
            msg:"",
        };
        this.editMessage=this.editMessage.bind(this);
        this.messageChange=this.messageChange.bind(this);
    }
    componentDidMount() {
        let path=`/editmessage/${this.props.match.params.id}`;//---------------------------获取旧的留言信息
            $.get(path).then((result) => {
                    if(result.status===200)
                    {
                        this.setState({
                            getmsg:result.msg,
                            user:this.props.match.params,
                            msg:result.msg.message,
                        });
                    }else {
                        console.log("获取！")
                    }
                },
                (error) => {
                    console.log(error);
                }
            )
        }
    editMessage(e){//-------------------------------修改留言
        let path=`/editmessage/${this.state.user.id}`;
        let msg=this.state.msg;
        if(msg!="") {
            $.post(path,{
                newmsg: msg,
            }).then((result) => {
                    if (result.status === 200) {
                        alert("修改成功！返回主页");
                        this.props.history.goBack();
                    } else {
                        console.log("修改失败！")
                    }
                },
                (error) => {
                    console.log(error);
                }
            )
        }else{
            alert("内容不能为空！");
        }
        e.preventDefault();
    }
    messageChange(e){//---------------------------修改后组件更新，监听input onChang 事件
        this.setState({msg:e.target.value});
    }
    render(){
        let temp=this.state;//----------------------------验证路径-------------
        let mpath=`/message/${temp.user.userName}/${temp.getmsg.userId}`;
        let lpath=`/home/${temp.user.userName}/${temp.getmsg.userId}`;
        mpath=temp.getmsg!=={}?mpath:null;
        lpath=temp.getmsg!=={}?lpath:null;//--------------------------------
        return <div className="msgIput">
            <h2><Link to={lpath} >留言列表</Link></h2>
            <h2><Link to={mpath} >我的留言</Link></h2>
            <h3><Link to='/'>退出</Link></h3>
            <h2>当前位置：修改留言</h2>
            <form className="head" onSubmit={this.editMessage} >
                <input  value={this.state.msg} onChange={this.messageChange}/>
                <button >修改</button>
            </form>
        </div>
    }
}